const {ipcMain} = require('electron');

const {
  close: closeMainWindow,
  minimize: minimizeMainWindow,
  send: sendMainWindow,
  show: showMAinWindow
} = require('../windows/main')
const {
  create: createControlWindow,
  send: sendControlWindow,
  close: closeControlWindow,
  minimize: minimizeControlWindow,
  maximize: maximizeControlWindow,
} = require('../windows/control')
// 在此处就会连接signal-server
const signal = require('./signalBus');
const signalTypes = require('../../signal_types');
const {settings_store} = require('../store');
const {log} = require('../../utils/log');

/**
 * 1. 处理单纯的 renderer进程 和 main进程 之间的通信
 *
 * 2. 处理ipc和signal混用, 其中最长的流程如下所示:
 *    (A客户端的renderA-1页面 向 B客户端的renderB-1页面 通信)
 *    rendererA-1 ---> mainA ---> signal-busA ---> signal-clientA
 *                                                              ↓
 *                                                        signal-server
 *                                                              ↓
 *    rendererB-1 ←--- mainB <--- signal-busB ---> signal-clientB
 */
const handleIPCAndSignal = () => {
  // ① 处理单纯的renderer进程和main进程之间的通信
  ipcMain.on(signalTypes.CLOSE_MAIN_WINDOW,  () => {
    closeMainWindow();
  });
  ipcMain.on(signalTypes.MINIMIZE_MAIN_WINDOW, () => {
    minimizeMainWindow();
  });
  ipcMain.on(signalTypes["CONTROL_WINDOW:CLOSE"],()=>{
    closeControlWindow();
  });
  ipcMain.on(signalTypes["CONTROL_WINDOW:MINIMIZE"], () => {
    minimizeControlWindow();
  });
  ipcMain.on(signalTypes["CONTROL_WINDOW:MAXIMIZE"], () => {
    maximizeControlWindow();
  });
  ipcMain.on(signalTypes["CONTROL_WINDOW:SHOW_MAIN_WINDOW"],()=>{
    showMAinWindow();
  })

  // ②
  // signal-client ---> signal-server ---> signal-client ---> signal-bus ---> ipc(main->renderer)
  signal.on(signalTypes["SIGNAL_SERVER:STATE_CHANGED"], (status) => {
    sendMainWindow(signalTypes["SIGNAL_SERVER:STATE_CHANGED"],status);
  });
  ipcMain.on(signalTypes["SIGNAL_SERVER:TRY_TO_CONNECT_FOR_SECONDS"],  () => {
    signal.emit(signalTypes["SIGNAL_SERVER:TRY_TO_CONNECT_FOR_SECONDS"]);
  });
  //
  signal.on(signalTypes["SIGNAL_SERVER:LOGINED"], (identifier_code) => {
    log('成功登录 ---> identifier_code:',identifier_code);
    settings_store.set('identifier_code', identifier_code);
    sendMainWindow(signalTypes["SIGNAL_SERVER:LOGINED"], identifier_code);
  });
  ipcMain.on(signalTypes["SIGNAL_SERVER:CONTROL"], (e, data) => {
    signal.send(signalTypes["SIGNAL_SERVER:CONTROL"], data);
  });
  signal.on(signalTypes["SIGNAL_SERVER:SUCCESSFUL_CONTROL"], async (be_controlled_code) => {
    log(`成功控制 ${be_controlled_code}`);

    let win = await createControlWindow(be_controlled_code);

    win.on('close', (e) => {
      log('control-window 即将关闭')
      // 发送控制方主动断开连接信号, 让被控制端也断开peer connection
      signal.send(signalTypes["SIGNAL_SERVER:CONTROL:FORWARD"], {
        event_type: signalTypes["CONTROL_WINDOW:CLOSE"],
        target_identifier_code:be_controlled_code
      });
      win = null;
    });
  });
  signal.on(signalTypes["CONTROL_WINDOW:CLOSE"], (data,sender_id) => {
    sendMainWindow(signalTypes["CONTROL_WINDOW:CLOSE"]);
  });
  signal.on(signalTypes["SIGNAL_SERVER:BE_CONTROLLED"], (controller_code) => {
    log(`被 ${controller_code} 控制了`);

    sendMainWindow(signalTypes["SIGNAL_SERVER:BE_CONTROLLED"], controller_code);
  });


  // 处理转发p2p通信需要的: candidate、offer、answer
  // ↓ 是renderer进程里提交上来的
  ipcMain.on(signalTypes["SIGNAL_SERVER:CONTROL:FORWARD"], (e, event_type, target_identifier_code, data) => {
    signal.send(signalTypes["SIGNAL_SERVER:CONTROL:FORWARD"], {
        event_type,
        target_identifier_code,
        data
      }
    );
  });
  signal.on('offer', (data) => {
    sendMainWindow('offer', data);
  });
  signal.on('answer',(data)=>{
    sendControlWindow('answer', data);
  })
  signal.on('puppet-candidate',(data)=>{
    sendControlWindow('candidate', data);
  })
  signal.on('control-candidate',(data)=>{
    sendMainWindow('candidate', data);
  })


  signal.on('error', (error) => {
    log('signal error:', error);

    //todo
    //  1. 是否给出弹框提示
    //  2. identifier_code重复是否自动重新申请
  });
};


module.exports = handleIPCAndSignal;
